#===============================================================================
# Koro Business Environment
# Copyright (C) 2008  Antonio Corroppoli
#
#This file is part of Koro BE.
# 
# Koro BE is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# Koro BE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Koro BE; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#===============================================================================

'''
Created on 20/ago/2011

@author: antstud
'''
import sys
from koro import util
from koro.core import exception
from koro import ksettings

class ModuleInfo(object):
    def __init__(self,version,dependency,description,weight):
        self.version=version
        self.dependency=dependency
        self.description=description
        self.weight=weight

#===============================================================================
# OpzioniDb
#===============================================================================
class InfoConnessione(dict):
    def __init__(self):
        dict.__init__(self)
        self['backend']='sqlite'
        self['dbname'] = ksettings.DB_PATH
        self['user']=''
        self['passwd']=''
        self['port']=''
        self['host']=''
        
    def __getattribute__(self,name):
        if name in self:
            return self[name]
        return super(InfoConnessione,self).__getattribute__(name)
    
    def __setattr__(self,name,value):
        if name in self:
            self[name]=value
            return
        super(InfoConnessione,self).__setattr__(name,value)


#===============================================================================
# Module
#===============================================================================
class Module(object):
    def __init__(self,name):
        self.name=name
        self.enabled=False
        self.module=None
        #self.dependency=None
        #self.description=''
        self.info=None
        self._configure()
    
    def _configure(self):
        name='koro.modules.{0}'.format(self.name)
        mod=__import__(name,fromlist=['info',])
        #self.dependency=mod.info.dependency
        #self.description=mod.info.description
        self.info=mod.info
    
    def load(self):        
        name='koro.modules.{0}'.format(self.name)
        __import__(name)
        self.module=sys.modules[name]
        self.enabled=True
    
    def get_dependency(self):
        if self.info.dependency is None:
            return ''
        d=''
        for item in self.info.dependency:
            d+='{0}, '.format(item.capitalize())
        return d
    
    def get_description(self):
        return self.info.description
    
    def get_version(self):
        return self.info.version
    
    def get_weight(self):
        return self.info.weight


#===============================================================================
# Modules
#===============================================================================
class Modules(dict):
    def __init__(self):
        self.__enabled_modules=[]
        
    def add(self,module):
        self[module.name]=module
    
    def load(self,name):
        mod=self[name]
        mod.load()
        self.__enabled_modules.append(mod)
    
    def all(self):
        all_modules=self.values()
        self._sort(all_modules)
        return tuple(all_modules)
    
    def enabled(self):
        self._sort(self.__enabled_modules)
        return tuple(self.__enabled_modules)
    
    def _sort(self,mod_list):
        if len(mod_list)==0:#evita loop infinito
            return 
        swap=True
        while swap:
            for i in range(len(mod_list)):
                if i==len(mod_list)-1:
                    swap=False
                    break
                if mod_list[i].get_weight()>mod_list[i+1].get_weight():
                    tmp=mod_list[i]
                    mod_list[i]=mod_list[i+1]
                    mod_list[i+1]=tmp
                    swap=True
                    break
                    


#===============================================================================
# Opzione
#===============================================================================
class Opzione(object):
    def __init__(self):
        self.chiave=''
        self.valore=''
    
    def validate(self):
        return
    

#==============================================================================
# Opzioni
#==============================================================================
class Opzioni(list):
    '''Mantiene una lista di oggetti Opzione. '''
    
    dirty=False
    
    @staticmethod
    def is_dirty():
        return Opzioni.dirty
    @staticmethod
    def set_dirty(dirty=True):
        Opzioni.dirty=dirty
    
    def __init__(self):
        super(Opzioni,self).__init__()
    
    def __getattribute__(self,name):
        for opt in self:
            if opt.chiave==name:
                return opt.valore
        try:
            attr=super(Opzioni,self).__getattribute__(name)
        except AttributeError:
            o=Opzione()
            o.chiave=name
            self.append(o)
            attr=o.valore
        return attr
    
    def __setattr__(self,name,value):
        for opt in self:
            if opt.chiave==name:
                opt.valore=str(value)
        return super(Opzioni,self).__setattr__(name,value)


#===============================================================================
# PersistentObject
#===============================================================================
class PersistentObject(object):
    def __init__(self):
        self.pending = True
        self.cascading = False
    
    def is_pending_object(self):
        if not hasattr(self,'pending'):
            self.pending=False
        return self.pending
    
    def is_cascading_object(self):
        return self.cascading
    
    def validate(self):
        raise exception.KoroInternalError('{0}.validate: interfaccia non implementata.'.format(self.__class__.__name__))


#===============================================================================
# IDObject
#===============================================================================
class IDObject(PersistentObject):
    def __init__(self):
        PersistentObject.__init__(self)
        self.ID=None
    
    def set_ID(self,value):
        self.ID=util.none_if_not(value)
        if self.ID is not None:
            self.ID=long(self.ID)
    
    def get_ID_fmt(self):
        return util.to_string(util.default_if_none(self.ID, u'')) 
    
    def get_ID(self):
        return self.ID

